<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    width="700px"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="订单编号" prop="orderCode">
        <el-input v-model="form.orderCode" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="form.projectId" placeholder="请选择项目" style="width: 100%">
          <el-option
            v-for="item in projectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%">
          <el-option
            v-for="item in supplierOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="form.startDate"
          type="date"
          style="width: 100%"
          placeholder="选择开始日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="form.endDate"
          type="date"
          style="width: 100%"
          placeholder="选择结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结算周期" prop="settlementCycle">
        <el-select v-model="form.settlementCycle" placeholder="请选择结算周期" style="width: 100%">
          <el-option
            v-for="dict in settlementCycleOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单金额" prop="totalAmount">
        <el-input-number v-model="form.totalAmount" :precision="2" :min="0" style="width: 100%" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed, PropType, watch, nextTick } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { addOrder, updateOrder } from "@/api/attendance/order";
import { OrderVO, OrderRequest } from "@/types/attendance/order";
import { handleFormError } from "@/utils/error-handler";

export default defineComponent({
  name: "OrderForm",
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    order: {
      type: Object as PropType<OrderVO>,
      default: () => ({})
    },
    projectOptions: {
      type: Array as PropType<Array<{ value: number; label: string }>>,
      default: () => []
    },
    supplierOptions: {
      type: Array as PropType<Array<{ value: number; label: string }>>,
      default: () => []
    }
  },
  emits: ["update:modelValue", "success"],
  setup(props, { emit }) {
    // 结算周期选项
    const settlementCycleOptions = [
      { value: "1", label: "月" },
      { value: "2", label: "季" },
      { value: "3", label: "年" },
      { value: "4", label: "自定义" }
    ];

    // 状态选项
    const statusOptions = [
      { value: "0", label: "进行中" },
      { value: "1", label: "已完成" },
      { value: "2", label: "已取消" }
    ];

    // 表单引用
    const formRef = ref<FormInstance>();

    // 表单数据
    const form = reactive<OrderRequest>({
      orderId: undefined,
      orderCode: "",
      projectId: undefined,
      supplierId: undefined,
      startDate: "",
      endDate: "",
      settlementCycle: "1",
      status: "0",
      totalAmount: 0,
      remark: ""
    });

    // 表单校验规则
    const rules = reactive<FormRules>({
      orderCode: [{ required: true, message: "订单编号不能为空", trigger: "blur" }],
      projectId: [{ required: true, message: "项目不能为空", trigger: "change" }],
      supplierId: [{ required: true, message: "供应商不能为空", trigger: "change" }],
      startDate: [{ required: true, message: "开始日期不能为空", trigger: "change" }],
      settlementCycle: [{ required: true, message: "结算周期不能为空", trigger: "change" }]
    });

    // 弹窗可见性
    const dialogVisible = computed({
      get: () => props.modelValue,
      set: (val: boolean) => {
        emit("update:modelValue", val);
      }
    });

    // 重置表单
    const resetForm = () => {
      form.orderId = undefined;
      form.orderCode = "";
      form.projectId = undefined;
      form.supplierId = undefined;
      form.startDate = "";
      form.endDate = "";
      form.settlementCycle = "1";
      form.status = "0";
      form.totalAmount = 0;
      form.remark = "";
      nextTick(() => {
        formRef.value?.resetFields();
      });
    };

    // 监听订单数据变化，初始化表单
    watch(
      () => props.order,
      val => {
        resetForm();
        if (val && val.orderId) {
          // 编辑模式，填充表单
          nextTick(() => {
            Object.assign(form, {
              orderId: val.orderId,
              orderCode: val.orderCode,
              projectId: val.projectId,
              supplierId: val.supplierId,
              startDate: val.startDate,
              endDate: val.endDate,
              settlementCycle: val.settlementCycle,
              status: val.status,
              totalAmount: val.totalAmount,
              remark: val.remark
            });
          });
        }
      },
      { immediate: true, deep: true }
    );

    // 监听对话框状态变化
    watch(
      () => dialogVisible.value,
      val => {
        if (!val) {
          resetForm();
        }
      }
    );

    // 提交表单
    const submitForm = () => {
      formRef.value?.validate(async valid => {
        if (valid) {
          try {
            const data = { ...form };

            if (form.orderId) {
              // 修改订单
              await updateOrder(data);
              ElMessage.success("修改成功");
            } else {
              // 新增订单
              await addOrder(data);
              ElMessage.success("新增成功");
            }

            dialogVisible.value = false;
            emit("success");
          } catch (error) {
            handleFormError(error, "订单");
          }
        }
      });
    };

    // 取消按钮
    const handleCancel = () => {
      dialogVisible.value = false;
      resetForm();
    };

    return {
      dialogVisible,
      form,
      rules,
      formRef,
      settlementCycleOptions,
      statusOptions,
      submitForm,
      handleCancel,
      resetForm
    };
  }
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>
